package com.BookManager.controller;

import com.BookManager.entity.Book;
import com.BookManager.entity.Lend;
import com.BookManager.entity.Student;
import com.BookManager.service.BookService;
import com.BookManager.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LendController {

    @Resource
    BookService bookService;

    @Resource
    UserService userService;

    @GetMapping({"/index", "/"})
    public String Lend(Model model){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        model.addAttribute("nickname",user.getUsername());
        model.addAttribute("studentCount",userService.getStudentList().size());
        model.addAttribute("bookCount",bookService.getBookMap().size());
        model.addAttribute("lendList",bookService.getLendList());
        model.addAttribute("adminCount",userService.getAccountList().size());
        return "index";
    }

    @GetMapping("/addLend")
    public String addLend(Model model){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        model.addAttribute("nickname",user.getUsername());
        model.addAttribute("bookList",bookService.getActiveBookList());
        model.addAttribute("studentList",userService.getStudentList());
        return "addLend";
    }

    @PostMapping("/addLend")
    public String addLend(int sid,int bid){
        bookService.addLend(sid,bid);
         return "redirect:/index";
    }

    @GetMapping("/returnBook")
    public String returnBook(int lid){
        bookService.returnBook(lid);
        return "redirect:/index";
    }

}
